package com.sinping.qh.api.admin.common;

import com.sinping.qh.api.support.Const;
import com.sinping.qh.api.support.ConstEum;
import com.sinping.qh.api.support.FrontPage;
import com.sinping.qh.api.support.ResDto;
import com.sinping.qh.domain.common.UnitDomain;
import com.sinping.qh.dto.admin.ApiUnitDto;
import com.sinping.qh.repository.mongo.UnitRepository;
import com.sinping.qh.service.admin.IUnitService;
import com.sinping.qh.utils.mapper.JsonMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 单位
 *
 * @author Tiansx
 * @create 2018-05-29 11:05
 **/
@Api(value = "admin基础信息管理", description = "基础信息管理API")
@RequestMapping(value = Const.ADMIN_URI, name = "基础信息管理")
@RestController
public class UnitEndPoint {
    @Autowired
    private Validator globalValidator;
    @Autowired
    private IUnitService iUnitService;

    @Autowired
    private UnitRepository unitRepository;

    private final static Logger logger = LoggerFactory.getLogger(UnitEndPoint.class);
    /**
     * 新增单位
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "新增单位", notes = "单位名称 // 不超过30个字符，不可重复<br>" +
            "单位类型 // 0:校级 1:院系级 <br>" )
    @RequestMapping(value = "unit", method = RequestMethod.POST, name = "新增单位")
    public ResDto insert(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"unit_name\":\"光电学院\",\"unit_type\":\"1\"}") @RequestParam(required = true) String msg) {
        ApiUnitDto apiUnitDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitDto.class);
        if (apiUnitDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }

        Set<ConstraintViolation<ApiUnitDto>> validate = globalValidator.validate(apiUnitDto);
        if (!validate.isEmpty()) {

            for (ConstraintViolation<ApiUnitDto> apiOrgSalesDTOConstraintViolation : validate) {
                logger.info("必传参数 :{}", apiOrgSalesDTOConstraintViolation.getMessage());
                return new ResDto(Const.PARAM_ERROR, apiOrgSalesDTOConstraintViolation.getMessage());
            }

        }
        if (!StringUtils.isNotBlank(apiUnitDto.getUnitType())) {
            logger.info("必传参数 :{}", "unit_type");
            return new ResDto(Const.PARAM_ERROR, "unit_type");
        }
        return  iUnitService.addUnit(request,apiUnitDto);


    }
    /**
     * 修改单位信息
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "修改单位信息", notes = "单位名称 // 不超过30个字符，不可重复<br>")
    @RequestMapping(value = "unit", method = RequestMethod.PUT, name = "修改单位信息")
    public ResDto update(HttpServletRequest request,@ApiParam(name = "msg", value = "{\"id\":\"1234\",\"unit_name\":\"光电学院\",\"unit_type\":\"1\"}") @RequestParam(required = true) String msg) {
        ApiUnitDto apiUnitDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitDto.class);
        if (apiUnitDto == null) {
            logger.error("参数为空或有不正确的数据格式");
            return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
        }
        if (!StringUtils.isNotBlank(apiUnitDto.getId())) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }
        if (!StringUtils.isNotBlank(apiUnitDto.getUnitType())) {
            logger.info("必传参数 :{}", "unit_type");
            return new ResDto(Const.PARAM_ERROR, "unit_type");
        }
        Set<ConstraintViolation<ApiUnitDto>> validate = globalValidator.validate(apiUnitDto);
        if (!validate.isEmpty()) {

            for (ConstraintViolation<ApiUnitDto> apiOrgSalesDTOConstraintViolation : validate) {
                logger.info("必传参数 :{}", apiOrgSalesDTOConstraintViolation.getMessage());
                return new ResDto(Const.PARAM_ERROR, apiOrgSalesDTOConstraintViolation.getMessage());
            }

        }
        return iUnitService.updateUnit(request,apiUnitDto);


    }
    /**
     * 删除单位信息
     *
     * @param id
     * @return ResDto
     */
    @ApiOperation(value = "删除单位信息")
    @RequestMapping(value = "unit/{id}", method = RequestMethod.DELETE, name = "删除单位信息")
    public ResDto delete(@ApiParam(name = "id", value = "245ad13d6ad4") @PathVariable String id) {

        if (StringUtils.isEmpty(id)) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }

        return iUnitService.deleteUnit(id);


    }

    /**
     * 获取单位详情
     * @param id
     * @return
     */
    @ApiOperation(value = "获取单位详情")
    @RequestMapping(value = "unit/{id}", method = RequestMethod.GET, name = "获取单位详情")
    public ResDto getUnitDetail(@ApiParam(name = "id", value = "245ad13d6ad4") @PathVariable String id) {

        if (StringUtils.isEmpty(id)) {
            logger.info("必传参数 :{}", "id");
            return new ResDto(Const.PARAM_ERROR, "id");
        }

        return iUnitService.getUnitDetail(id);


    }
    /**
     * 单位列表,分页
     *
     * @param msg
     * @return ResDto
     */
    @ApiOperation(value = "单位列表,分页")
    @RequestMapping(value = "unit_page", method = RequestMethod.GET, name = "单位列表,分页")
    public ResDto listPage(@ApiParam(name = "msg", value = "{\"page_size\":10, \"page_current\":1, \"order_column\":null, \"order_by\":null, \"condition\":{\"unit_name\":\"log\",\"unit_type\":\"1\"}}") @RequestParam(required = true) String msg) {

        try {
            logger.info("入参 {}", msg);
            //1.String msg=> FrontPage page
            FrontPage page = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
            if (page == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            ResDto resDto = iUnitService.getUnitList(page);
            return resDto;
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR,"数据解析异常");
            return resDto;
        }

    }

    /**
     * 单位列表,不分页
     * @return
     */
    @ApiOperation(value = "单位列表,不分页",notes = "unit_type:单位类型 0：校级 1：院系  ，获取全部类型的单位传空串;" +
            "<br> status:单位状态，0：单位有效;获取全部状态的单位传空串\"")
    @RequestMapping(value = "unit", method = RequestMethod.GET, name = "单位列表，不分页")
    public ResDto list(@ApiParam(name = "msg", value = "{\"unit_type\":\"1\",\"status\":\"0\"}") @RequestParam(required = true) String msg) {

        try {
            logger.info("入参 {}", msg);

            ApiUnitDto apiUnitDto = JsonMapper.defaultMapper().fromJson(msg, ApiUnitDto.class);
            if (apiUnitDto == null) {
                logger.error("参数为空或有不正确的数据格式");
                return new ResDto(Const.PARAM_ERROR, "参数为空或有不正确的数据格式");
            }
            ResDto resDto = iUnitService.getUnitList(apiUnitDto.getUnitType(),apiUnitDto.getStatus());
            return resDto;
        } catch (Exception e) {
            logger.error("数据解析异常{}", e);
            ResDto resDto = new ResDto(Const.SERVER_ERROR,"数据解析异常");
            return resDto;
        }

    }


    /**
     * 自动审核
     */
    @ApiOperation(value = "自动审核")
    @RequestMapping(value = "/auto_review",method = RequestMethod.POST,name = "自动审核")
    public ResDto autoReview(HttpServletRequest httpServletRequest,@ApiParam(name = "msg",value = "{\"unitIds\":[\"6666\",\"6666\"],\"isSetAuto\":\"1\"}") @RequestParam(required = true) String msg){


        if (StringUtils.isBlank(msg)){
            return new ResDto(Const.PARAM_ERROR,"参数msg不能为空");
        }

        Map<String,Object> map = JsonMapper.defaultMapper().fromJson(msg, Map.class);
        String isSetAuto = map.get("isSetAuto").toString();
        List<String> units = (List<String>) map.get("unitIds");


        boolean updateSuccess = false;
        for (String unitId:units) {
            UnitDomain unitDomain = unitRepository.findOne(unitId);
            if (unitDomain != null){
                unitDomain.setIsAutomatic(isSetAuto);
                UnitDomain save = unitRepository.save(unitDomain);
                if (save != null){
                    updateSuccess = true;
                }
            }

        }
        if (updateSuccess){
            return new ResDto(Const.SUCCESS,"成功");
        }
        else {
            return new ResDto(Const.SERVER_ERROR,"没有更新记录");
        }


    }

    @ApiOperation("已自动审核的院系列表")
    @RequestMapping(value = "/has_auto_review",method = RequestMethod.GET,name = "已自动审核的院系列表")
    public ResDto getHasReviewed(){

        try {
            //单位类型 0：校级  1：院系    自动审核：0：不自动  1：自动
            List<UnitDomain> list = unitRepository.findAllByUnitTypeAndIsAutomaticAndStatus("1","1","0");
            String listStr = JsonMapper.defaultMapper().toJson(list);
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setDatas(listStr);
            resDto.setMsg("成功");
            return resDto;
        }
        catch (Exception e){
            return new ResDto(Const.SERVER_ERROR,"查询异常");
        }

    }
}
